package com.agentpad.util;

import java.util.ArrayList;
import java.util.List;

import com.agentpad.House;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class HouseDbHelper {
	private Context context;
	private SQLiteDatabase database;
	private DatabaseHelper dbHelper;
	private static final String DATABASE_TABLE = "t_house";

	public HouseDbHelper(Context context) {
		this.context = context;
	}

	public void open() throws SQLException {
		dbHelper = new DatabaseHelper(context);
		database = dbHelper.getWritableDatabase();
//		database.execSQL("DROP TABLE IF EXISTS t_house");
//		database.execSQL("CREATE TABLE t_house (_id integer primary key autoincrement, col_name text not null, col_addr text not null, col_struct text not null, col_pic text)");
	}

	public void close() {
		dbHelper.close();
	}

	public long insertHouse(String name, String addr, String struct, String pic) {
		ContentValues values = new ContentValues();
		values.put("col_name", name);
		values.put("col_addr", addr);
		values.put("col_struct", struct);
		values.put("col_pic", pic);
		
		return database.insert(DATABASE_TABLE, null, values);
	}
	
	public boolean updateHouse(long rowId, String name, String addr, String struct, String pic) {
		ContentValues values = new ContentValues();
		values.put("col_name", name);
		values.put("col_addr", addr);
		values.put("col_struct", struct);
		values.put("col_pic", pic);

		return database.update(DATABASE_TABLE, values, "_id=" + rowId, null) > 0;
	}
	
	public boolean deleteHouse(long rowId) {
		return database.delete(DATABASE_TABLE, "_id=" + rowId, null) > 0;
	}
	
	public List<House> getHouses()
	{
		 Cursor cur = database.query(DATABASE_TABLE, new String[] {"_id", "col_name", "col_addr", "col_struct", "col_pic" }, 
				 null, null, null, null, null);
		 
		 List<House> houses = new ArrayList<House>(); 
		 cur.moveToFirst();
		 while(!cur.isAfterLast())
		 {
			 House house = new House(cur.getString(1), cur.getString(2), cur.getString(3), cur.getString(4));
			 house.setId(cur.getLong(0));
			 houses.add(house);
			 cur.moveToNext();
		 }
		 
		 return houses;
	}

//	public List<String> getHouseNames()
//	{
//		 List<String> houses = new ArrayList<String>(); 
//		 Cursor cur = database.query(DATABASE_TABLE, new String[] {"col_name"}, null, null, null, null, null);
//		 
//		 cur.moveToFirst();
//		 while(!cur.isAfterLast())
//		 {
//			 String name = cur.getString(0);
//			 houses.add(name);
//			 cur.moveToNext();
//		 }
//		 
//		 return houses;
//	}
}
